<template>
	<!-- 主路由 -->
	<router-view class="app_router" v-slot="{ Component }">
		<keep-alive>
			<component
				v-if="$route.meta.keepAlive"
				:key="$route.name"
				:is="Component"
			/>
		</keep-alive>
		<component
			v-if="!$route.meta.keepAlive"
			:key="$route.name"
			:is="Component"
		/>
	</router-view>
</template>

<script setup>
import { useRouter } from 'vue-router'
import bjsdk from '@/libs/beta-jsdk'

const router = useRouter()
const isShare = bjsdk.query('fS') === '1' // 是否为分享场景

window.bjsdk = bjsdk
window.router = router

/**
 * <START>本地化signet、hasPrivate参数解析
 */
// 其他理财师的signet(分享时手动拼接到链接)
const querySignet = bjsdk.query('signet')
// 及时授权获取到的signet
const hashSignet = bjsdk.query('signet', location.hash)
// 已授权缓存在本地的signet
const localSignet = localStorage.getItem('signet')
// 本人授权获取到的signet
const userSignet = hashSignet || localSignet
if (userSignet) localStorage.setItem('signet', userSignet)
// 本次打开应用已授权标志位(用于刷新页面判断，无需重新授权)
if (hashSignet) sessionStorage.setItem('__hasAuth__', '1')
// 判断是否需要重新授权
const hasAuth = sessionStorage.getItem('__hasAuth__') === '1'
// 通过删除bjwt值发起重新授权 (需要在外部浏览器联调，暂时只在微信环境下清除bjwt)
if (!hasAuth && bjsdk.isGWX) localStorage.removeItem('bjwt')
// hasPrivate解析
const hashPrivate = bjsdk.query('hasPrivate', location.hash)
if (hashPrivate) sessionStorage.setItem('__hasPrivate__', hashPrivate)
const hasPrivate = sessionStorage.getItem('__hasPrivate__') === '1'
/** <END>本地化signet参数解析 */

// 外部调试
bjsdk.query('_signet') && localStorage.setItem('signet', bjsdk.query('_signet'))
bjsdk.query('_bjwt') &&
	(localStorage.setItem('bjwt', bjsdk.query('_bjwt')),
	localStorage.setItem('bjwte', 19999999999999999))

/**
 * <START>本地化jsdk配置
 */
const bjsdkConfig = () => {
	const HOOK_REG =
		/^((https?:)?\/\/)?[\w\-_]+(\.[\w\-_]+)*(\.betawm.com)([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/ // eslint-disable-line
	const isMinePath =
		location.pathname === `${process.env.VUE_APP_PublicPath}/mine`
	const authChannel = querySignet ? 'mp' : '' // 授权渠道
	const authType =
		isMinePath && !authChannel && !hasPrivate
			? 'private' // 我的页面走高级授权
			: 'base' // 默认走静默授权
	const clientType = bjsdk.isMobile ? 'MOBILE' : 'PC'
	bjsdk.config({
		// 默认禁止分享
		shareOps: {
			enable: 0,
		},
		//服务器列表
		servers: {
			...process.env.SERVERS_ENV,
			hook: (urlOps) => (urlOps.hook = HOOK_REG.test(urlOps.url)),
			// 配置该参数，接口不走rp代理
			proxy: (urlOps) => (urlOps.proxy = false),
		},
		wxOps: {
			debug: false,
			apiRoot: '/BetaCS.BackGateway/wx',
			authUrl: `/BetaCS.BackGateway/wx/Auth?authChannel=${authChannel}&authType=${authType}&clientType=${clientType}`,
			openTagList: ['wx-open-launch-weapp'],
			jsApiList: ['chooseImage'], // 必填，随意一个接口即可
			agentApi: ['getCurExternalContact', 'sendChatMessage'],
		},
		navOps: {
			// signet 本地化uparms参数
			pass: [
				'CorpId',
				'SuiteId',
				'isRef',
				'bjwt',
				'uparms',
				'fS',
				'sTime',
				'signet',
				'vdebug',
				'_bjwt',
				'_signet',
			],
			reqAbsPath: false, //将url转换为绝对路径
			/**
			 * 混淆Url,防止封禁
			 * 0：表示不混淆，
			 * 2：表示跟随当页面Url
			 * 其他值：表示混淆；
			 * 混淆用的随机串默认为时间戳+随机数，当confuse为字符串值表示参数名，即从目标Url参数获取值来允当随机串
			 */
			confuse: 0,

			//router是异步方法，需强制同步刷新页面
			async nav(ops, navOps) {
				const locationKey = location.pathname + location.search
				window._pageCacheGoToHooks?.[locationKey] &&
					Object.values(
						window._pageCacheGoToHooks[locationKey]
					).forEach((_) => bjsdk.isFunc(_) && _(ops?.path))

				//jsdk路由处理
				const _goPage = (_url, _rpc = false) => {
					_url = _url.replace(/^((https?:)?\/\/)?/, '$2//')
					if (_rpc) window.location.replace(_url)
					else window.location.href = _url
				}
				const _url = ops.url || ''
				const rpc = navOps.replace || false //是否用replace
				if (
					// eslint-disable-next-line
					/^((https?:)?\/\/)?[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(
						_url
					) ||
					navOps.isAbsPath
				) {
					_goPage(_url, rpc)
					return
				}

				const p = ops.path || ''
				const par = { ...ops.queryObj }
				// 跳转授权路径
				if (p.startsWith(`/BetaCS.BackGateway/wx`)) {
					_goPage(_url, true)
					return
				}
				// 兼容 光大项目根目录存在路径
				if (p.startsWith(process.env.VUE_APP_RootPath)) {
					_goPage(_url, false)
					return
				}
				if (p.indexOf('/') == 0) {
					await router.push({
						path: p,
						replace: rpc,
						query: par,
					})
				} else {
					await router.push({
						name: p,
						replace: rpc,
						params: par,
					})
				}
			},
		},
		// 日志配置
		logOps: {
			limit: 0,
		},
	})
}
bjsdkConfig()
/** <END>本地化jsdk配置 */
</script>

<style lang="less" scoped>
@import '~@CSS/share.less';
.app_router {
	flex: 1;
}
</style>
